package com.bz.common;

import java.util.HashMap;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.bz.entity.BaseDto;
import com.bz.security.AuthUserDto;

@Component
// @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) })
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
              @Signature(type = Executor.class,
                         method = "query",
                         args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })

public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object[] args = invocation.getArgs();
        // MappedStatement ms = (MappedStatement) args[0];
        // Object parameterObject = args[1];
        // BoundSql boundSql = ms.getBoundSql(parameterObject);
        // String sql = boundSql.getSql();
        //
        // if (ArrayUtils.isNotEmpty(args)) {
        // if (args[1] == null) {
        // args[1] = new MapperMethod.ParamMap<>();
        // }
        // Map map = (Map) args[1];
        // // 此处为重点
        //// map.put("test", "aaaaaaaaaaaa");
        // }
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            Object obj = auth.getPrincipal();
            if (obj instanceof AuthUserDto) {
                AuthUserDto authUserDto = (AuthUserDto) auth.getPrincipal();
                Object param = args[1];
                if (param != null && param instanceof HashMap) {
                    // System.out.println(param);
                    // ((HashMap)param).put("namePhone", "Karen");
//                    ((HashMap) param).put("_roleMap", authUserDto.getRoleMap());
//                    ((HashMap) param).put("_userId", authUserDto.getId());
                } else if (param != null && param instanceof BaseDto) {
                    // if(StringUtils.isNotEmpty(authUserDto.getOrganizationId())) {
//                    if (null == ((BaseDto) param).get_roleMap()) {
//                        ((BaseDto) param).set_roleMap(authUserDto.getRoleMap());
//                        ((BaseDto) param).set_userId(authUserDto.getId());
//                    }
                    // }
                    // System.out.println(param);
                }
            }

        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        // return Plugin.wrap(target, this);
        // if (o instanceof StatementHandler) {
        // return Plugin.wrap(o, this);
        // }
        // return o;
        if (o instanceof Executor) {
            // 如果是Executor（执行增删改查操作），则拦截下来
            return Plugin.wrap(o, this);
        } else {
            return o;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        // System.out.println(properties);
    }

}